﻿using System;
using System.Collections.Generic;
using System.Linq;
using CoreAudioApi;

namespace SoftPhone
{
    public partial class frmDeviceSetting : DevExpress.XtraEditors.XtraForm
    {
        public frmDeviceSetting()
        {
            InitializeComponent();
            InitialLoad();
        }

        
        private List<MMDevice> devices = new List<MMDevice>();
        private void InitialLoad()
        {
            MMDeviceEnumerator deEnum = new MMDeviceEnumerator();
            var allDevice = deEnum.EnumerateAudioEndPoints(EDataFlow.eAll, EDeviceState.DEVICE_STATE_ACTIVE);
            var devCount = allDevice.Count;
            for (var i = 0; i < devCount; i++)
            {
                var device = allDevice[i];
                devices.Add(device);
            }

            var input = devices.Where(a => a.DataFlow == EDataFlow.eCapture).ToList();
            var output = devices.Where(a => a.DataFlow == EDataFlow.eRender).ToList();

            cbxPlaybackdevice.DisplayMember = "FriendlyName";
            cbxPlaybackdevice.ValueMember = "ID";
            cbxPlaybackdevice.DataSource = output;

            cbxRecordDevice.DisplayMember = "FriendlyName";
            cbxRecordDevice.ValueMember = "ID";
            cbxRecordDevice.DataSource = input;

            var outDeviceDefault = deEnum.GetDefaultAudioEndpoint(CoreAudioApi.EDataFlow.eRender, CoreAudioApi.ERole.eMultimedia);
            var inDeviceDefault = deEnum.GetDefaultAudioEndpoint(CoreAudioApi.EDataFlow.eCapture, CoreAudioApi.ERole.eMultimedia);
            cbxPlaybackdevice.SelectedValue = outDeviceDefault.ID;
            cbxRecordDevice.SelectedValue = inDeviceDefault.ID;
        }

        internal void SetDefaultDeviceByID(string devName)
        {
            foreach (var device in devices.Where(device => device.FriendlyName == devName))
            {
                PolicyConfigClient policy = new PolicyConfigClient();
                policy.SetDefaultEndpoint(device.ID, ERole.eMultimedia);
            }
        }        

        private void btnOK_Click(object sender, EventArgs e)
        {
            if (cbxPlaybackdevice.SelectedValue != null)
            {
                var deviceID = cbxPlaybackdevice.SelectedValue.ToString();
                SetDefaultDeviceByID(devices.Where(a => a.ID == deviceID).SingleOrDefault().FriendlyName);
            }

            if (cbxRecordDevice.SelectedValue != null)
            {
                var deviceID = cbxRecordDevice.SelectedValue.ToString();
                SetDefaultDeviceByID(devices.Where(a => a.ID == deviceID).SingleOrDefault().FriendlyName);
            }

            this.Close();
        }

        private void btnCancel_Click(object sender, EventArgs e)
        {
            this.Close();
        }

    }
}